using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace AI
{
    public class WalkEdgeTurnAround : MonoBehaviour
    {
        [SerializeField]
        private Vector2 testOffsetVector2 = new Vector2(0.5f, 0.5f);
        [SerializeField]
        private float rayDistance = 0.25f;

        [SerializeField]
        private LayerMask whatIsGround;


        private Dir moveDir;
        private GameUnit owner;
        void Start()
        {
            owner = GetComponent<GameUnit>();

            moveDir = Random.Range(0,2) == 0 ? Dir.LEFT : Dir.RIGHT;
            moveDir = Dir.RIGHT;
            owner.FaceDir = moveDir;
            if (moveDir == Dir.LEFT) {
                owner.Rb.velocity = new Vector2(-owner.Speed, 0);
            }
            else {
                owner.Rb.velocity = new Vector2(owner.Speed, 0);
            }
        }

        void Update()
        {

            //测试右边
            var or = testOffsetVector2 + new Vector2(transform.position.x, transform.position.y);
            var hitRight = Physics2D.Raycast(or, Vector2.down, rayDistance, whatIsGround);
            //测试左边
            var ol = new Vector2(transform.position.x - testOffsetVector2.x, transform.position.y + testOffsetVector2.y);
            var hitLeft = Physics2D.Raycast(ol, Vector2.down, rayDistance, whatIsGround);

            if (hitRight.collider == null) {
                Debug.Log("发现右边是悬崖！");
                SetMoveDir(Dir.LEFT);
            } 
            else if (hitLeft.collider == null) {
                SetMoveDir(Dir.RIGHT);
            }
            
        }

        void SetMoveDir(Dir dir) {
            moveDir = dir;
            owner.FaceDir = moveDir;
            if (moveDir == Dir.LEFT) {
                owner.Rb.velocity = new Vector2(-owner.Speed, 0);
            }
            else {
                owner.Rb.velocity = new Vector2(owner.Speed, 0);
            }
        }

        private void OnDrawGizmos()
        {
            Gizmos.color = Color.red;
            
            var or = testOffsetVector2 + new Vector2(transform.position.x, transform.position.y);
            var ol = new Vector2(transform.position.x - testOffsetVector2.x, transform.position.y + testOffsetVector2.y);

            Gizmos.DrawLine(or, or + new Vector2(0, -rayDistance));
            Gizmos.DrawLine(ol, ol + new Vector2(0, -rayDistance));
        }
    }

}

